package com.groupmobile.quotes;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import android.app.AlertDialog;
import android.app.ExpandableListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.TextView;
import android.widget.Toast;

import com.groupmobile.quotes.database.DatabaseQuote;

public class AuthorIndex extends ExpandableListActivity {

	ExpandableListView expList;
	DatabaseQuote mDatabaseQuote;
	
	ArrayList<ClassGroup> group = new ArrayList<ClassGroup>();
	ArrayList<ArrayList<ClassItem>> item = new ArrayList<ArrayList<ClassItem>>();
	ExpAdapter mExpAdapter = null;
	
	Comparator<ClassItem> comperator_name, comperator_name_image;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.author_index);
		
		comperator_name = new Comparator<ClassItem>() {
			@Override
			public int compare(ClassItem object1, ClassItem object2) {
				return object1.name.compareToIgnoreCase(object2.name);
			}
		};
		comperator_name_image = new Comparator<ClassItem>() {
			@Override
			public int compare(ClassItem object1, ClassItem object2) {
				return object1.name_image.compareToIgnoreCase(object2.name_image);
			}
		};
		
		mDatabaseQuote = new DatabaseQuote(this);
		mDatabaseQuote.openDatabase();
		String[] columns =new String[]{mDatabaseQuote.AUTHOR_id, mDatabaseQuote.AUTHOR_name, mDatabaseQuote.AUTHOR_name_image};
		Cursor mCursor = mDatabaseQuote.getCursorQuery(mDatabaseQuote.AUTHOR_TABLE, columns, null, null, null, null, mDatabaseQuote.AUTHOR_name + " ASC");
		
		String NameGroup = "";//Tên của group
		ClassGroup mClassGroup = null;
		ArrayList<ClassItem> chi1 = null;

		while(mCursor.moveToNext()){
			
			String AUTHOR_id =  mCursor.getString(mCursor.getColumnIndex(mDatabaseQuote.AUTHOR_id));
			String AUTHOR_name = mCursor.getString(mCursor.getColumnIndex(mDatabaseQuote.AUTHOR_name));
			String AUTHOR_name_image = mCursor.getString(mCursor.getColumnIndex(mDatabaseQuote.AUTHOR_name_image));
			
			if(!NameGroup.startsWith(AUTHOR_name.substring(0, 1))){
				NameGroup = AUTHOR_name.substring(0, 1);
				
				if(chi1 != null){
					Collections.sort(chi1, comperator_name);
					item.add(chi1);
					}
				
				mClassGroup = new ClassGroup(NameGroup);
				group.add(mClassGroup);
				
				chi1 = new ArrayList<ClassItem>();
				ClassItem it1 = new ClassItem(AUTHOR_id, AUTHOR_name, AUTHOR_name_image);
				chi1.add(it1);
			}else{
				ClassItem it1 = new ClassItem(AUTHOR_id, AUTHOR_name, AUTHOR_name_image);
				chi1.add(it1);
			}
			
			System.out.println("AUTHOR_name="  + AUTHOR_name.substring(0, 1));
			//if(NameGroup.startsWith(AUTHOR_name.substring(1, end)))
		}
		//Thêm các item cuối cùng
		if(chi1 != null)
			item.add(chi1);
		
		mCursor.close();
		mDatabaseQuote.closeDatabase();
		
		expList = getExpandableListView();
		mExpAdapter = new ExpAdapter(this);
		expList.setAdapter(mExpAdapter);
		expList.collapseGroup(1);
		expList.setFastScrollEnabled(true);

		expList.setOnGroupExpandListener(new OnGroupExpandListener() {
			public void onGroupExpand(int groupPosition) {
				//Log.e("onGroupExpand", "OK");
			}
		});

		expList.setOnGroupCollapseListener(new OnGroupCollapseListener() {
			public void onGroupCollapse(int groupPosition) {
				//Log.e("onGroupCollapse", "OK");
			}
		});

		expList.setOnChildClickListener(new OnChildClickListener() {
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				//Log.e("OnChildClickListener", "OK");
				return false;
			}
		});
		
		expList.setOnScrollListener(new AbsListView.OnScrollListener() {			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				//System.out.println("firstVisibleItem = " + firstVisibleItem);
				//System.out.println("view = " + view.getChildCount());
				try{
					TextView tvGroupName = (TextView) view.getChildAt(0).findViewById(R.id.gi_header);
					System.out.println("tvGroupName = " + tvGroupName.getText());
					//Toast.makeText(AuthorIndex.this, tvGroupName.getText(), Toast.LENGTH_SHORT).show();
				}catch(Exception e){
					System.out.println("e = " + e.toString());
					try{
						TextView tvPlayerName = (TextView) view.getChildAt(0).findViewById(R.id.ai_author_name);
						System.out.println("tvPlayerName = " + tvPlayerName.getText());
						//Toast.makeText(AuthorIndex.this, tvPlayerName.getText().toString().substring(1, 2), Toast.LENGTH_SHORT).show();
					}catch(Exception e1){
						System.out.println("e1 = " + e1.toString());
					}
				}
				//System.out.println("visibleItemCount = " + visibleItemCount);
				//System.out.println("totalItemCount = " + totalItemCount);
				//System.out.println();
				
			}
		});
	}

	int item_select = 0;
	public void OnClickAuthorIndexButton(View v) {
		final CharSequence[] items = {"Sort authors by First Name", "Sort authors by Surname"};

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Sorting:");
		builder.setSingleChoiceItems(items, item_select, new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int item) {
		    	if(item_select != item){
		    		item_select = item;
		    		sort(item);
		    	}
		        Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
		        dialog.dismiss();
		    }
		});
		AlertDialog alert = builder.create();
		alert.show();
	}
	
	public void sort(int index){
		for(int i=0;i<item.size();i++){
			ArrayList<ClassItem> it = item.get(i);
			if(index == 0)
				Collections.sort(it, comperator_name);
			else Collections.sort(it, comperator_name_image);
		}
		mExpAdapter.notifyDataSetChanged();
	}

	public void onActionBarLogoClicked(View v) {
		this.finish();
	}
	
	class ClassGroup{
		public String nameGroup;
		ClassGroup(String nameGroup){
			this.nameGroup = nameGroup;
		}
		public String getNameGroup(){
			return this.nameGroup;
		}
	}
	
	class ClassItem{
		public String id;
		public String name;
		public String name_image;
		
		public ClassItem(String id,String name, String name_image){
			this.id = id;
			this.name = name;
			this.name_image = name_image;
		}
		
		public String getId(){
			return this.id;
		}
		
		public String getName(){
			return this.name;
		}
		
		public String getName_image(){
			return this.name_image;
		}
	}

	public class ExpAdapter extends BaseExpandableListAdapter {

		private Context myContext;

		public ExpAdapter(Context context) {
			myContext = context;
		}

		public Object getChild(int groupPosition, int childPosition) {
			return null;
		}

		public long getChildId(int groupPosition, int childPosition) {
			return 0;
		}

		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {

			if (convertView == null) {
				LayoutInflater inflater = (LayoutInflater) myContext
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = inflater.inflate(R.layout.author_index_item, null);
			}

			ArrayList<ClassItem> l = item.get(groupPosition);
			ClassItem cl = l.get(childPosition);
			
			TextView tvPlayerName = (TextView) convertView.findViewById(R.id.ai_author_name);
			tvPlayerName.setText(cl.getName());
			
			Button ai_about_author_btn = (Button) convertView.findViewById(R.id.ai_about_author_btn);
			ai_about_author_btn.setBackgroundDrawable(getDrawable(cl.getName_image()));

			return convertView;
		}

		public int getChildrenCount(int groupPosition) {
			ArrayList<ClassItem> l = item.get(groupPosition);
			return l.size();
		}

		public Object getGroup(int groupPosition) {
			return null;
		}

		public int getGroupCount() {
			return group.size();
		}

		public long getGroupId(int groupPosition) {
			return 0;
		}

		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {

			if (convertView == null) {
				LayoutInflater inflater = (LayoutInflater) myContext
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = inflater.inflate(R.layout.generic_index_header_item, null);
			}

			TextView tvGroupName = (TextView) convertView.findViewById(R.id.gi_header);
			ClassGroup cl = group.get(groupPosition);
			tvGroupName.setText(cl.getNameGroup());

			expList.expandGroup(groupPosition);
			return convertView;
		}

		public boolean hasStableIds() {
			return false;
		}

		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}
	}
	
	//------------------------------------------------------------
	public Drawable getDrawable(String name) {
		Drawable drawable = null;
		try{
			Resources res = getResources();
			int resID = res.getIdentifier(name, "drawable", getPackageName());
			drawable = res.getDrawable(resID);
		}catch(Exception e){
			Resources res = getResources();
			int resID = res.getIdentifier("kalam", "drawable", getPackageName());
			drawable = res.getDrawable(resID);
		}
		return drawable;
	}

}
